<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ currentUserInfo.name }}</span>
      </div>
      <div class="content">
        <div class="avatar" @click="updateAvatar">
          <el-tooltip content="点击头像可更换头像" placement="top" effect="light">
            <el-avatar shape="square" :size="64" :src="currentUserInfo.userface" :alt="currentUserInfo.username" />
          </el-tooltip>
        </div>
        <div class="section">
          电话号码：
          <el-tag size="mini">{{ currentUserInfo.telephone }}</el-tag>
        </div>
        <div class="section">
          手机号码：
          <el-tag size="mini">{{ currentUserInfo.phone }}</el-tag>
        </div>
        <div class="section">
          地址：
          <el-tag size="mini">{{ currentUserInfo.address }}</el-tag>
        </div>
        <div class="section">
          角色：
          <span v-for="role in currentUserInfo.roles" :key="role.id"><el-tag size="mini" type="success">{{ role.nameZh }}</el-tag></span>
        </div>
        <div class="btn">
          <el-button size="small" type="primary" @click="updateInfo">修改信息</el-button>
          <el-button size="small" type="danger" @click="updatePassword">修改密码</el-button>
        </div>
      </div>
    </el-card>

    <el-dialog title="修改用户信息" :visible.sync="dialogVisibleInfo" width="20%" :close-on-click-modal="false" :show-close="false" center class="user-info-edit">
      <div style="display: flex;justify-content: center">
        <table>
          <tr>
            <td>用户昵称：</td>
            <td><input v-model="currentUserInfoEdit.name" type="text"></td>
          </tr>
          <tr>
            <td>电话号码：</td>
            <td><input v-model="currentUserInfoEdit.telephone" type="text"></td>
          </tr>
          <tr>
            <td>手机号码：</td>
            <td><input v-model="currentUserInfoEdit.phone" type="text"></td>
          </tr>
          <tr>
            <td>联系地址：</td>
            <td><input v-model="currentUserInfoEdit.address" type="text"></td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="onCancelInfo">取 消</el-button>
        <el-button size="small" type="primary" @click="onConfirmInfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改密码" :visible.sync="dialogVisiblePassword" width="20%" :close-on-click-modal="false" :before-close="handleClosePassword" center class="user-info-edit">
      <div style="display: flex;justify-content: center">
        <el-form ref="ruleForm" size="small" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="旧密码" prop="oldPass">
            <el-input v-model="ruleForm.oldPass" type="password" placeholder="请输入旧密码" autocomplete="off" />
          </el-form-item>
          <el-form-item label="新密码" prop="pass">
            <el-input v-model="ruleForm.pass" type="password" placeholder="请输入新密码" autocomplete="off" />
          </el-form-item>
          <el-form-item label="确认新密码" prop="checkPass">
            <el-input v-model="ruleForm.checkPass" type="password" placeholder="请再次输入新密码" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog title="更换头像" :visible.sync="dialogVisibleAvatar" width="20%" :close-on-click-modal="false" :before-close="handleCloseAvatar" center class="user-info-edit">
      <div style="display: flex;justify-content: center">
        <el-upload
          class="avatar-uploader"
          action="/common/file/upload?remark=vhr"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleCloseAvatar">取 消</el-button>
        <el-button size="small" type="primary" @click="onConfirmInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { GetCurrentUserInfo, UpdateCurrentUserInfo, UpdatePassword } from '@/api/Profile'
import { FastDFSAccessUrl } from '@/utils/global'

export default {
  name: 'Profile',
  data() {
    var validateOldPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      currentUserInfo: {},
      currentUserInfoEdit: {},
      dialogVisibleInfo: false,
      dialogVisiblePassword: false,
      dialogVisibleAvatar: false,
      imageUrl: '',
      ruleForm: {
        oldPass: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        oldPass: [
          { validator: validateOldPass, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getCurrentUserInfo()
  },
  methods: {
    getCurrentUserInfo() {
      GetCurrentUserInfo().then((res) => {
        if (res) {
          this.currentUserInfo = res
          this.currentUserInfoEdit = Object.assign({}, this.currentUserInfo)
        }
      })
    },
    updateInfo() {
      this.dialogVisibleInfo = true
    },
    onCancelInfo() {
      this.dialogVisibleInfo = false
      this.currentUserInfoEdit = Object.assign({}, this.currentUserInfo)
    },
    onConfirmInfo() {
      UpdateCurrentUserInfo(this.currentUserInfoEdit).then((res) => {
        if (res) {
          this.dialogVisibleInfo = false
          this.getCurrentUserInfo()
          window.sessionStorage.setItem('user', JSON.stringify(this.currentUserInfoEdit))
          this.$store.dispatch('user/updateName', this.currentUserInfoEdit.name)
          this.$store.dispatch('user/updateAvatar', this.currentUserInfoEdit.userface)
          this.handleCloseAvatar()
        }
      })
    },
    updatePassword() {
      this.dialogVisiblePassword = true
    },
    handleClosePassword() {
      this.dialogVisiblePassword = false
      this.ruleForm = {
        oldPass: '',
        pass: '',
        checkPass: ''
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          UpdatePassword({
            oldPass: this.ruleForm.oldPass,
            pass: this.ruleForm.pass,
            checkPass: this.ruleForm.checkPass,
            id: this.currentUserInfo.id
          }).then((res) => {
            if (res) {
              this.handleClose()
              this.logout()
            }
          })
        }
      })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    updateAvatar() {
      this.dialogVisibleAvatar = true
    },
    handleCloseAvatar() {
      this.dialogVisibleAvatar = false
      this.imageUrl = ''
      this.currentUserInfoEdit = Object.assign({}, this.currentUserInfo)
    },
    handleAvatarSuccess(res) {
      this.imageUrl = FastDFSAccessUrl + res.object.url
      this.currentUserInfoEdit.userface = this.imageUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!(isJPG || isPNG)) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang='scss' scope>
.box-card {
  width: 400px;

  .content {
    .avatar {
      display: flex;
      justify-content: center;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .section {
      font-size: 14px;
      line-height: 2em;
    }

    .btn {
      margin-top: 10px;
      display: flex;
      justify-content: space-around;
    }
  }
}

.user-info-edit .el-dialog__body {
  padding: 10px 0 !important;
}

.user-info-edit {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
